<!--
 * @LastEditTime : 2022-11-03 15:51:54
 * @FilePath     : /pyy/src/views/equipment/add/index.vue
 * @Description  : 设备计量 > 设备计量校准(新增)
-->
<template>
  <div id="equipment-add">
    <van-nav-bar title="设备计量校准委托单" left-arrow @click-left="goBack" />

    <div class="contaniner">
      <van-form
        label-width="180px"
        ref="infoFrom"
        input-align="right"
        error-message-align="right"
        validate-trigger="onChange"
        scroll-to-error
        @submit="handleSubmit"
      >
        <div class="form-group">
          <van-field
          class="mandatory"
            autosize
            rows="1"
            type="textarea"
            name="ywwtfkhmc"
            label="委托方（客户）名称"
            label-width="max-content"
            :rules="[{ required: true, message: '不能为空' }]"
            placeholder="请填写"
            autocomplete="off"
            v-model="form.ywwtfkhmc"
          />
          <van-field
          class="mandatory"
            name="ywwtr"
            label="客户委托人"
            placeholder="请填写"
            :rules="[{ required: true, message: '不能为空' }]"
            autocomplete="off"
            v-model="form.ywwtr"
          />
          <van-field
          class="mandatory"
            autosize
            rows="1"
            type="textarea"
            name="ywdz"
            label="地址"
            label-width="max-content"
            :rules="[{ required: true, message: '不能为空' }]"
            placeholder="请填写"
            autocomplete="off"
            v-model="form.ywdz"
          />
          <van-field
          class="mandatory"
            name="ywdh"
            label="电话"
            placeholder="请填写"
            autocomplete="off"
            :rules="[
              
              { required: true, message: '电话不能为空' },
            ]"
            v-model="form.ywdh"
          />
          <!-- <van-field
            readonly
            autosize
            rows="1"
            type="textarea"
            name="calibratorName"
            label="校准方名称"
            label-width="max-content"
            placeholder="请填写"
            autocomplete="off"
            v-model="form.calibratorName"
          /> -->
          <!-- <van-field
            readonly
            autosize
            rows="1"
            type="textarea"
            name="calibratorAddress"
            label="地址"
            label-width="max-content"
            placeholder="请填写"
            autocomplete="off"
            v-model="form.calibratorAddress"
          /> -->
          <!-- <van-field
            readonly
            name="calibratorPhone"
            label="电话"
            placeholder="请填写"
            autocomplete="off"
            :rules="[
              {
                validator: (val) =>
                  !val
                    ? true
                    : /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(
                        val
                      ) || /^((\d{3,4}-)|\d{3.4}-)?\d{7,8}$/.test(val),
                message: '请输入正确的电话号码',
              },
            ]"
            v-model="form.calibratorPhone"
          /> -->
          <popup-select
          class="mandatory2"
            name="rkbs"
            label="认可标识"
            placeholder="请选择"
            :options="relationData.identificationOptions"
            :default-props="{
              label: 'name',
              value: 'id',
            }"
            :rules="[{ required: true, message: '不能为空' }]"
            v-model="form.rkbs"
          />
          <van-field name="sfjj " label="是否需要加急">
            <template #input>
              <van-radio-group direction="horizontal" v-model="form.sfjj">
                <van-row type="flex" justify="space-between">
                  <van-col
                    v-for="item in relationData.whetherOptions"
                    :key="item.id"
                  >
                    <radio-circle :name="item.id" icon-size="16px">
                      {{ item.name }}
                    </radio-circle>
                  </van-col>
                </van-row>
              </van-radio-group>
            </template>
          </van-field>
          <popup-select
          class="mandatory2"
            name="bjsbfs"
            label="送校方式"
            :rules="[{ required: true, message: '不能为空' }]"
            placeholder="请选择"
            :options="relationData.toWayOptions"
            :default-props="{
              label: 'name',
              value: 'id',
            }"
            v-model="form.bjsbfs"
          />
          <van-field name="jzbzsfty" label="校准标准是否同意">
            <template #input>
              <van-radio-group direction="horizontal" v-model="form.jzbzsfty">
                <van-row type="flex" justify="space-between">
                  <van-col
                    v-for="item in relationData.whetherOptions"
                    :key="item.id"
                  >
                    <radio-circle :name="item.id" icon-size="16px">
                      {{ item.name }}
                    </radio-circle>
                  </van-col>
                </van-row>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
          class="mandatory"
            autosize
            rows="1"
            type="textarea"
            name="khzddjzff"
            label="指定校准方法"
            label-width="max-content"
            placeholder="请填写"
            autocomplete="off"
            v-model="form.khzddjzff"
            :rules="[{ required: true, message: '不能为空' }]"
            v-if="calibrationStandard"
          />
          <van-field
            autosize
            rows="1"
            type="textarea"
            class="describe"
            name="describe"
            label="其它约定"
            label-width="100%"
            input-align="left"
            placeholder="请输入其它约定内容"
            autocomplete="off"
            v-model="form.qtyd"
          />
          <!-- <van-field name="simplify" label="简化合同评审">
            <template #input>
              <van-radio-group direction="horizontal" v-model="form.simplify">
                <van-row type="flex" justify="space-between">
                  <van-col
                    v-for="item in relationData.whetherOptions"
                    :key="item.id"
                  >
                    <radio-circle :name="item.id" icon-size="16px">
                      {{ item.name }}
                    </radio-circle>
                  </van-col>
                </van-row>
              </van-radio-group>
            </template>
          </van-field> -->
          <!-- <van-field
            name="contractNo"
            label="合同号"
            placeholder="请填写"
            autocomplete="off"
            v-model="form.contractNo"
          /> -->
          <!-- <calendar
    
            name="wtfwtrq"
            label="委托日期"
            placeholder="请选择日期"
            class="entrustment mandatory2"
            v-model="form.wtfwtrq"
            :rules="[{ required: true, message: '不能为空' }]"
          /> -->
          <van-field
                label="委托日期"
                readonly
                clickable
                name="wtfwtrq"
                class="entrustment mandatory2"
                :value="form.wtfwtrq"
                placeholder="请选择日期"
                @click="showCalendar = true"
                :rules="[{ required: true, message: '不能为空' }]"
                right-icon="arrow"
            />
            <van-calendar v-model="showCalendar"  @confirm="clientTimeConfirm" />

          <!-- <van-field
            type="number"
            name="calibrationAmount"
            label="校准金额(元)"
            readonly
            placeholder="请填写数字"
            autocomplete="off"
            :formatter="(value) => Number(value) || null"
            v-model="form.calibrationAmount"
          /> -->
          <!-- <van-field
            type="number"
            name="paidAmount"
            label="实收金额(元)"
            readonly
            placeholder="请填写数字"
            autocomplete="off"
            :formatter="(value) => Number(value) || null"
            v-model="form.paidAmount"
          /> -->
        </div>
        <!-- <van-button
          block
          type="default"
          class="btn-import-detailed"
          :icon="importIcon"
          native-type="button"
          @click="importData"
        >
          下载模板
        </van-button>
        <van-uploader
          :file-list="fileList"
          max-count="1"
          :before-read="beforeRead"
          :after-read="afterRead"
          accept="all"
        >
         
        </van-uploader> -->

        <van-button
          block
          type="default"
          class="btn-import-detailed"
          :icon="importIcon"
          native-type="button"
          @click="importData"
        >
          导入数据
        </van-button>
        <!-- <van-button type="primary" text="导入数据" @click="show = true" />
      <van-overlay :show="show" @click="show = false">
      <div class="wrapper" @click.stop>
        <div class="block" />
        <van-button
          block
          type="default"
          class="btn-import-detailed"
          :icon="importIcon"
          native-type="button"
          @click="importData"
        >
        导入数据       
        </van-button>
      </div>
    </van-overlay> -->

        <detailed
          v-for="(item, index) in form.child"
          :key="'detailed_' + index"
          :index="index"
          :show-delete="index < form.child.length - 1"
          :form.sync="item"
          :sample-state="relationData.sampleStateOptions"
          :detection-big="relationData.detectionOptions"
          :categoryOptions="relationData.equipmentUnderTestCategory"
          :isOrNo="relationData.whetherOptions"
          :importDataIs="importDataIs"
          @delete="(i) => form.child.splice(i, 1)"
          @copy="copyMethod"
        />
        <van-button
          block
          type="default"
          class="btn-add-detailed"
          icon="plus"
          native-type="button"
          @click.stop="handleAddDetailed"
          style="margin-top: 10px"
        >
          新增明细
        </van-button>
        <div class="btn-groups">
          <van-button
            class="btn-submit"
            round
            block
            type="info"
            native-type="submit"
          >
            提交
          </van-button>
        </div>
      </van-form>
    </div>

    <van-uploader
      v-show="false"
      :file-list="fileList"
      max-count="1"
      :after-read="afterRead"
      accept=".xlsx"
      multiple
      ref="uploaderRef"
    >
      &nbsp;
    </van-uploader>
  </div>
</template>

<script>
import Detailed from "./components/detailed.vue";
import { Toast } from "vant";
import api from "@/http/api";
import { Dialog } from "vant";
import { BASEURL } from "@/http/apiUrl";
import { ACCESS_TOKEN } from "@/http/apiUrl";

export default {
  name: "EquipmentAdd",
  components: {
    Detailed,
    [Dialog.Component.name]: Dialog.Component,
  },
  data() {
    return {
      show: false,
      fileList: [],
      showDielog: false,
           // 委托日期
           showCalendar: false,
      importDataIs: "",
      checkedUrgent: "", //是否加急
      importIcon: require("../../../assets/images/import.png"),
      relationData: {
        // 认可标识
        identificationOptions: [],
        // 送样方式
        toWayOptions: [],
        // 被测设备类别
        equipmentUnderTestCategory: [],
        // 是否
        whetherOptions: [
          // {
          //   name:'是',
          //   id:'1'
          // },
          // {
          //   name:'否',
          //   id:'2'
          // },
        ],
      },

      form: {
        ywwtfkhmc: "",
        ywwtr: "",
        ywdz: "",
        ywdh: "",
        // calibratorName: "四川攀研检测技术有限公司",
        // calibratorAddress: "四川省攀枝花市桃园街90号",
        // calibratorPhone: "0812-3380591",
        rkbs: "",
        bjsbfs: "",
        jzbzsfty: "",
        sfjj: "",
        khzddjzff: "",
        qtyd: "",
        // simplify: "",
        // contractNo: "",
        wtfwtrq: "",
        // calibrationAmount: "",
        // paidAmount: "",
        child: [
          //{
          //  equipmentName: "",
          //  equipmentCode: "",
          //  specification: "",
          //  category: "",
          //  num: "",
          //  pointName: "",
          //  certificationUnit: "",
          //  isAdjustment: "",
          //  isRequire: "",
          //  isSeal: "",
          //  sfjj: "",
          //},
        ],
      },

    };
  },
  created() {
    this.initRelationData();
  },
  computed: {
    // 校准标准 是否
    calibrationStandard() {
      const result = this.relationData.whetherOptions.find(
        (item) => item.id == this.form.jzbzsfty
      );
      return result ? result.name == "否" : false;
    },
  },
  mounted() {
    this.form.wtfwtrq = this.getNowDate()
  },
  methods: {
    getNowDate() {
      const timeOne = new Date()
      const year = timeOne.getFullYear()
      let month = timeOne.getMonth() + 1
      let day = timeOne.getDate()
      month = month < 10 ? '0' + month : month
      day = day < 10 ? '0' + day : day
      const NOW_MONTHS_AGO = `${year}-${month}-${day}`
      return NOW_MONTHS_AGO
    },
    // 委托日期
    clientTimeConfirm(date) {
            this.form.wtfwtrq = `${date.getFullYear()}-${
                date.getMonth() + 1
            }-${date.getDate()}`;
            this.showCalendar = false;
        },
    // 复制明细表
    copyMethod(i) {
      this.importDataIs = "2"; //复制明细行判定
      this.form.child.push(JSON.parse(JSON.stringify(this.form.child[i])));
    },

    beforeRead(file) {
      if (file.type !== ".xlsx") {
        Toast("请上传.xlsx 格式文件");
        return false;
      }
      return true;
    },
    afterRead(file) {
      let formData = new FormData();
      formData.append("file", file.file);
      api.equipment.uploadAFile(formData).then((res) => {
        const { code, data = [] } = res.data;
        if (code === 200) {
          let arr = [];
          res.data.data.forEach((item) => {
            arr.push(this.enumerationTraversal(item));
          });
          // 导入的数据  类别是中文 不是id  无法提交
          let isNoCategory = this.relationData.equipmentUnderTestCategory;
          for (var i = 0; i < arr.length; i++) {
            for (var j = 0; j < isNoCategory.length; j++) {
              if (arr[i].lb == isNoCategory[j].name) {
                arr[i].lb = isNoCategory[j].id;
              }
            }
          }
          this.form.child.push(...arr);
          this.importDataIs = "1"; //导入数据判定
          let isNoArr = this.relationData.whetherOptions;

          for (var i = 0; i < this.form.child.length; i++) {
            if (this.form.child[i].sfxtz == "是") {
              this.form.child[i].sfxtz = isNoArr[0].id;
            } else {
              this.form.child[i].sfxtz = isNoArr[1].id;
            }
            if (this.form.child[i].sfxwx == "是") {
              this.form.child[i].sfxwx = isNoArr[0].id;
            } else {
              this.form.child[i].sfxwx = isNoArr[1].id;
            }
            if (this.form.child[i].sfxfy == "是") {
              this.form.child[i].sfxfy = isNoArr[0].id;
            } else {
              this.form.child[i].sfxfy = isNoArr[1].id;
            }
          }
        }
      });
    },
    // 枚举
    enumerationTraversal(item) {
      return {
        bclsbmc: item["被测量设备名称"], //被测量设备名称
        bh: item["编号"], //编号
        xhgg: item["型号规格"], //型号规格
        lb: item["类别"], //类别
        ypsl: item["数量"], //样品数量
        cldmc: item["测量点名称"], //测量点名称
        zsdw: item["证书单位"], //证书单位
        sfxtz: item["是否需调整"], //是否需要调整
        sfxwx: item["是否需修理"], //是否需要修理
        sfxfy: item["是否需封印"], //是否需要封印
      };
    },
    // 导入数据弹框
    importData() {
      Dialog.confirm({
        title: "",
        confirmButtonText: "下载",
        cancelButtonText: "导入",
        message:
          "请点击右边【下载】按钮下载数据导入Excel模板，填写并保存后再点击左边的【导入】按钮导入该Excel模板",
      })
        .then(() => {
          // on confirm
          console.log("下载模板 :>> ");
          // api.equipment.downloadTheTemplate().then(() => {});
          // const url =`${BASEURL}/file/downloadSlsxTemplate?access_token=${localStorage.frameToken}`;
          // const url = `${BASEURL}/file/downloadSlsxTemplate?access_token=${ACCESS_TOKEN}`;
          const url = `${BASEURL}/webjars/myzfile/downloadSlsxTemplate`;
          this.getBlob(url, "设备计量校准委托信息明细表");
        })
        .catch(() => {
          // on cancel
          console.log("上传文件 :>> ");
          this.$refs.uploaderRef.chooseFile();
        });
    },
    /**
     * 根据 url请求地址 获取文件流
     * @param {string} url: 请求地址
     * @return {Promise<Blob>} 获取结果
     */
    getBlob(url, fileName) {
      // url =  http://10.2.207.209:8080/file/downloadSlsxTemplate?access_token=829dbc9a-551c-43bf-af60-ba3ec4c5432b
      const tmpa = document.createElement("a");
      tmpa.download = fileName || "下载";
      tmpa.href = url;
      // 触发下载
      tmpa.click();
    },
    /**
     * 返回
     */
    goBack() {
      this.$router.replace({ name: "Equipment" });
    },

    /**
     * 初始化 关联数据
     */
    initRelationData() {
      const toast = Toast.loading({
        duration: 0,
        forbidClick: true,
      });
      api.equipment
        .getEnumeratedValues()
        .then((res) => {
          const { code, data, msg } = res.data || {};
          if (code !== 200) return Toast.fail(msg);
          // console.log('枚举data :>> ', data);
          this.relationData.identificationOptions =
            data["计量校准-认可标识"] || [];
          this.relationData.toWayOptions = data["被校设备送校方式"] || [];
          this.relationData.whetherOptions = data["是否"] || [];
          this.relationData.equipmentUnderTestCategory =
            data["被测量设备类别"] || [];
          this.setDefaultData();
        })
        .finally(() => {
          setTimeout(toast.clear, 500);
        });
    },

    /**
     * 设置 默认数据
     */
    setDefaultData() {
      // 默认选中 是
      const result = this.relationData.whetherOptions[0] || {};
      this.form.jzbzsfty = result.id;
      // this.form.dispose = result.id;
      this.form.sfjj = result.id;
    },

    /**
     * 点击 新增明细表
     */
    handleAddDetailed() {
      this.importDataIs = "9";
      this.form.child.push({
        bclsbmc: "", //被测量设备名称
        bh: "", //编号
        xhgg: "", //型号规格
        lb: "", //类别
        ypsl: "", //样品数量
        cldmc: "", //测量点名称
        zsdw: "", //证书单位
        sfxtz: "", //是否需要调整
        sfxwx: "", //是否需要修理
        sfxfy: "", //是否需要封印
      });
    },

    /**
     * 点击 提交
     */
    handleSubmit() {
      const toast = Toast.loading({
        duration: 0,
        forbidClick: true,
      });
      api.equipment
        .submitOrders({
          ...this.form,
          //  analysisSum: this.analysisSum,
        })
        .then((res) => {
          const { code, msg } = res.data || {};
          if (code !== 200) return Toast.fail(msg);
          Toast.success("新增成功");
          setTimeout(this.goBack, 1000);
        })
        .finally(() => {
          setTimeout(toast.clear, 500);
        });
      console.log("submit", this.form);
    },
  },
};
</script>

<style lang="less" scoped>
#equipment-add {
  width: 100vw;
  height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
  .wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .block {
    width: 120px;
    height: 120px;
    background-color: #fff;
  }
  /deep/ .van-nav-bar {
    .van-nav-bar__title {
      font-family: "Inter";
      font-style: normal;
      font-weight: 600;
      font-size: 18px;
      line-height: 20px;
      text-align: center;
      letter-spacing: -0.24px;
      color: #333333;
    }

    .van-nav-bar__content {
      .van-nav-bar__left {
        i {
          font-size: 20px;
          color: #999999;
        }
      }
    }
  }

  .contaniner {
    width: 100%;
    height: 0;
    flex: 1;
    overflow-y: auto;
    box-sizing: border-box;
    padding: 10px;

    /deep/ .van-form {
      .van-uploader {
        display: block;
      }
      .van-uploader__wrapper {
        display: block;
      }
      .form-group {
        box-sizing: border-box;
        padding: 0 12px;
        background: #ffffff;
        .mandatory{
            position: relative;
            &::after{
                content: '*';
                display: block;
                position: absolute;
                left: 5px;
                top: 14px;
                font-size: 16px;
                color: red;
                transform: scale(1);

            }
        }
        .mandatory2{
            position: relative;
            &::after{
                content: '*';
                display: block;
                position: absolute;
                left: 5px;
                top: 20px;
                font-size: 16px;
                color: red;
                transform: scale(1);

            }
        }
        .van-radio-group--horizontal {
          flex-wrap: nowrap;
          .van-radio__icon--round .van-icon {
            background-color: transparent;
          }
          .van-radio__icon--checked .van-icon {
            &:before {
              content: "";
              display: inline-block;
              width: 0.55em;
              height: 0.55em;
              background-color: #1989fa;
              border-radius: 50%;
              position: relative;
              top: -2px;
            }
          }
        }

        .entrustment .van-cell {
          border-bottom: none;
        }
        .select .van-cell__title {
          width: auto !important;
        }
      }
      .van-button__content .van-button__text {
        margin-left: 10px;
      }
      .btn-import-detailed {
        margin: 10px 0;

        .van-button__content {
          color: #0e86d1;

          .van-button__text {
            font-size: 0.42667rem;
            position: relative;
            top: 1px;
          }
        }
      }
      .van-field {
        font-family: "Inter";
        font-style: normal;
        font-weight: 400;
        font-size: 16px;
        line-height: 24px;
        color: #666666;
        padding: 12px 4px;
        padding-left: 15px !important;
        border-bottom: 1px solid #e8e8e8;

        .van-field__label {
          span {
            white-space: nowrap;
          }
        }

        .van-field__value {
          .van-field__body {
            .van-field__control {
              .van-radio-group {
                width: 80%;

                .van-row {
                  width: 100%;

                  .van-radio {
                    margin: 0;

                    .van-radio__icon {
                      height: 16px;
                      width: 16px;

                      .svg-icon {
                        height: 16px;
                        width: 16px;
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }

      // 其它约定
      .van-field.describe {
        flex-direction: column;
        border: none;

        .van-field__value {
          flex: none;
          width: 100%;
          min-height: 108px;
          background: #f8f8f8;
          box-sizing: border-box;
          padding: 8px 12px;
          margin-top: 6px;
          font-size: 14px;
        }
      }

      .btn-add-detailed {
        font-family: "ABeeZee";
        font-style: normal;
        font-weight: 400;
        font-size: 16px;
        line-height: 20px;
        text-align: center;
        letter-spacing: -0.24px;
        color: #0e86d1;
        border: none;
      }
    }

    .btn-groups {
      width: 100%;
      box-sizing: border-box;
      padding: 18px 12px;

      .btn-submit {
        background: #0e86d1;
        border-radius: 4px;
        font-family: "Inter";
        font-style: normal;
        font-weight: 400;
        font-size: 16px;
        line-height: 19px;
        color: #ffffff;
      }
    }
  }
}
</style>
